package com.chang.bootplus.controller;




import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chang.bootplus.base.annotation.PublicVisit;
import com.chang.bootplus.base.exception.BusException;
import com.chang.bootplus.base.utils.ApiResponse;

import com.chang.bootplus.base.utils.BeanUtil;
import com.chang.bootplus.base.utils.HttpUtil;
import com.chang.bootplus.base.utils.OpenIdJson;
import com.chang.bootplus.config.wx.WxProperties;
import com.chang.bootplus.controller.storage.local.LocalService;
import com.chang.bootplus.controller.storage.local.LocalYml;
import com.chang.bootplus.entity.Student;
import com.chang.bootplus.entity.WxUser;
import com.chang.bootplus.po.*;
import com.chang.bootplus.service.StudentService;
import com.chang.bootplus.service.WxUserService;
import com.chang.bootplus.vo.StudentBindVO;
import com.chang.bootplus.vo.WxUsersDetailVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.http.*;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author chang
 * @since 2022-01-23
 */
@Api(tags = {"微信用户"})
@RestController
@RequestMapping("/wx-user")
public class WxUserController {

//    private String appID = "wxe4373d7e3eca0b4b";
//    private String appSecret = "65a0c6ff322b584e3756da4eb9a5d205";

    @Autowired
    WxProperties wxProperties;

    @Autowired
    WxUserService wxUserService;

    @Autowired
    StudentService studentService;

    @Autowired
    LocalService service;

    @PublicVisit
    @PostMapping("/storage")
    @ApiOperation(httpMethod = "POST", value = "存储 / 更新 微信用户openid和微信名称和头像")
    public ApiResponse<Void> storage(@RequestBody WxUserDetailPO po){
        WxUser wxUser = BeanUtil.beanA2beanB(po, WxUser.class);
        if(wxUserService.getOne(new LambdaQueryWrapper<WxUser>().eq(WxUser::getOpenId,po.getOpenId())) == null){
            boolean save = wxUserService.save(wxUser);
            if(!save){
                throw new BusException("存储失败");
            }
        }
        else{
            boolean update = wxUserService.update(wxUser, new LambdaQueryWrapper<WxUser>().eq(WxUser::getOpenId, po.getOpenId()));
            if(!update){
                throw new BusException("更新失败");
            }
        }

        return new ApiResponse().setReMsg("存储/更新 成功");
    }

    @PublicVisit
    @PostMapping("/getOpenId")
    @ApiOperation(httpMethod = "POST", value = "code转openId")
    public ApiResponse<Void> getOpenId(@RequestBody WxCodePO po) throws IOException {
        String code = po.getCode();
        String result = "";
        try{//请求微信服务器，用code换取openid。HttpUtil是工具类，后面会给出实现，Configure类是小程序配置信息，后面会给出代码
            result = HttpUtil.doGet(
                    "https://api.weixin.qq.com/sns/jscode2session?appid="
                            + wxProperties.getAppId() + "&secret="
                            + wxProperties.getAppSecret() + "&js_code="
                            + code
                            + "&grant_type=authorization_code", null);
        }
        catch (Exception e) {
            throw new BusException("请求微信服务器异常");
        }


        ObjectMapper mapper = new ObjectMapper();
        OpenIdJson openIdJson = null;
        try{
            openIdJson = mapper.readValue(result,OpenIdJson.class);
        }catch (Exception e){
            throw new BusException("code异常");
        }


        return new ApiResponse().setReMsg(openIdJson.getOpenid());
    }

    @PublicVisit
    @PostMapping("/checkOpenId")
    @ApiOperation(httpMethod = "POST", value = "验证openid是否绑定学生，1是绑定，0是未绑定")
    public ApiResponse<StudentBindVO> checkOpenId(@RequestBody WxUserPO po){
        List<Student> list = studentService.list(new LambdaQueryWrapper<Student>().eq(Student::getOpenId, po.getOpenId()));
        if (list.size()==0){
            return new ApiResponse().setReMsg("0");
        }
        Student one = list.get(0);

        if(one == null){
            return new ApiResponse().setReMsg("0");
        }

        StudentBindVO studentBindVO = new StudentBindVO();
        studentBindVO.setUsername(one.getUsername()).setStuId(one.getStuId()).setGradeId(one.getGradeId().substring(1));
        return new ApiResponse<>(studentBindVO).setReMsg("1");
    }

    @PostMapping("/listWxUsers")
    @ApiOperation(httpMethod = "POST", value = "查询所有的用户信息,输入微信名则为按照微信名模糊查询")
    public ApiResponse<WxUsersDetailVO> listWxUsers(@RequestBody WxUserListPO po){
        Page<WxUser> page = new Page<>(po.getPageNumber(), po.getPageSize());
        Page<WxUser> pages = wxUserService.page(page, new LambdaQueryWrapper<WxUser>()
                .like(po.getNickname() != null && !po.getNickname().isEmpty() ,WxUser::getNickname,po.getNickname()));

        List<WxUser> records = pages.getRecords();
        List<WxUsersDetailVO> wxUsersDetailVOS = new ArrayList<>();
        records.stream().forEach(wxUser -> {
            WxUsersDetailVO wxUsersDetailVO = BeanUtil.beanA2beanB(wxUser,WxUsersDetailVO.class);
            List<Student> list = studentService.list(new LambdaQueryWrapper<Student>().eq(Student::getOpenId, wxUser.getOpenId()));
            if(list == null || list.size() == 0){
                wxUsersDetailVO.setStatus(0).setLoginType("学校登录");
            }

            else{
                Student one = list.get(0);
                if(one == null){
                    wxUsersDetailVO.setStatus(0).setLoginType("学校登录");
                }else{
                    wxUsersDetailVO.setStatus(1).setLoginType("学校登录").setStuId(one.getStuId());
                }
            }

            wxUsersDetailVOS.add(wxUsersDetailVO);
        } );
        return new ApiResponse<>(wxUsersDetailVOS);
    }







}

